package com.service.system.agent.impl;

import com.dao.*;
import com.entity.AgentRankVo;
import com.entity.system.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.service.system.agent.AgentService;
import com.util.Const;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AgentServiceImpl implements AgentService{

    @Autowired
    AgentMapper agentMapper;

    @Autowired
    AgentIncomeMapper agentIncomeMapper;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    AgentNewMapper agentNewMapper;

    @Autowired
    HatProvinceMapper hatProvinceMapper;

    @Autowired
    HatCityMapper hatCityMapper;

    @Autowired
    HatAreaMapper hatAreaMapper;

    @Autowired
    AgentIncomeDetailNewMapper agentIncomeDetailNewMapper;

    @Autowired
    OrderMapper orderMapper;

    @Override
    public Map<String, Object> findAgentList(Map<String, String> map) {
        Map<String ,Object> map1 = new HashMap<>();
        int pageNum = 1;
        int pageSize = 10;
        if(StringUtils.isNotEmpty(map.get("pageNum"))){
           pageNum = Integer.parseInt(map.get("pageNum"));
        }
        if(StringUtils.isNotEmpty(map.get("pageSize"))){
            pageSize = Integer.parseInt(map.get("pageSize"));
        }
        PageHelper.startPage(pageNum,pageSize);
        List<AgentNew> list = agentNewMapper.selectListVo(map);
        PageInfo<AgentNew> pageInfo = new PageInfo<>(list);
        List<AgentNew> agentNews = pageInfo.getList();
        for(AgentNew agentNew : agentNews){
            UserInfo user = userInfoMapper.findUserById(agentNew.getUserId());
            if(null != user){
                agentNew.setPhone(user.getPhone());
                agentNew.setNickName(user.getNickName());
            }
            HatProvince hatProvince = hatProvinceMapper.findByProvinceId(agentNew.getProvinceCode());
            if(null != hatProvince){
                agentNew.setProvinceCode(hatProvince.getProvince());
            }
            HatCity hatCity = hatCityMapper.findByCityId(agentNew.getCityCode());
            if(null != hatCity){
                agentNew.setCityCode(hatCity.getCity());
            }
            HatArea hatArea = hatAreaMapper.findByAreaId(agentNew.getCountyCode());
            if(null != hatArea){
                agentNew.setCountyCode(hatArea.getArea());
            }
        }
        map1.put("code", Const.SUCCESS_CODE);
        map1.put("message","查询成功");
        map1.put("agents",agentNews);
        map1.put("page",pageInfo);
        return map1;
    }

    @Override
    public Map<String, Object> findAgentIncomeList(Map<String, Object > map) {
        Map<String,Object> map1 = new HashMap<>();
        int pageNum = 1;
        int pageSize = 10;
        if(StringUtils.isNotEmpty(map.get("pageNum").toString())){
            pageNum = Integer.parseInt(map.get("pageNum").toString());
        }
        if(StringUtils.isNotEmpty(map.get("pageSize").toString())){
            pageSize = Integer.parseInt(map.get("pageSize").toString());
        }

        Map<String,Object> map2 = null;
        if(StringUtils.isNotEmpty(map.get("phone").toString())){
            map2 = userInfoMapper.findUserIdByPhone(map.get("phone").toString());
            if(null != map2){
                map.put("userId",map2.get("id")+"");
            }else {
                map1.put("code",Const.ERROR_CODE);
                map1.put("message","查无数据");
                return map1;
            }
        }
        //根据当前登录用户代理级别查询代理商表的userid
        List<Long> userIds = agentNewMapper.findUserIdByMap(map);
        if(userIds.size() <= 0){
            map1.put("code",Const.ERROR_CODE);
            map1.put("message","查无数据");
            return map1;
        }
        map.put("userIds",userIds);
        PageHelper.startPage(pageNum,pageSize);
        List<AgentIncomeDetailNew> list = agentIncomeDetailNewMapper.findByMap(map);
        PageInfo<AgentIncomeDetailNew> pageInfo = new PageInfo<>(list);
        List<AgentIncomeDetailNew> agentIncomeDetailNews = pageInfo.getList();
        for(AgentIncomeDetailNew agentIncomeDetailNew : agentIncomeDetailNews){
            //商家广告收益
            Map<String,Object> map3 = new HashMap<>();
            map3.put("incomeUserId",agentIncomeDetailNew.getIncomeUserId());
            map3.put("incomeType",11);
            agentIncomeDetailNew.setBusinessAdvertIncome(agentIncomeDetailNewMapper.findSumIncomeAmountByUserIdAndIncomeType(map3).divide(new BigDecimal(100)));
            //区域广告收益
            map3.put("incomeType",21);
            agentIncomeDetailNew.setAreaAdvertIncome(agentIncomeDetailNewMapper.findSumIncomeAmountByUserIdAndIncomeType(map3).divide(new BigDecimal(100)));
            //推荐收益
            map3.put("incomeType",31);
            agentIncomeDetailNew.setRecommendedIncome(agentIncomeDetailNewMapper.findSumIncomeAmountByUserIdAndIncomeType(map3).divide(new BigDecimal(100)));
            //优惠买单收益
            map3.put("incomeType",41);
            agentIncomeDetailNew.setConsumerIncome(agentIncomeDetailNewMapper.findSumIncomeAmountByUserIdAndIncomeType(map3).divide(new BigDecimal(100)));
            //总收益
            agentIncomeDetailNew.setSumIncome(agentIncomeDetailNew.getBusinessAdvertIncome().add(agentIncomeDetailNew.getAreaAdvertIncome()).add(agentIncomeDetailNew.getRecommendedIncome().add(agentIncomeDetailNew.getConsumerIncome())));

            AgentNew agentNew = agentNewMapper.findByUserId(agentIncomeDetailNew.getIncomeUserId());
            if(null != agentNew){
                agentIncomeDetailNew.setAgentName(agentNew.getAgentName());
                if(agentNew.getAgentLevel() == 1){
                    agentIncomeDetailNew.setAgentLevelStr("区县代理");
                }else if(agentNew.getAgentLevel() == 2){
                    agentIncomeDetailNew.setAgentLevelStr("市级代理");
                }else if(agentNew.getAgentLevel() == 3){
                    agentIncomeDetailNew.setAgentLevelStr("省级代理");
                }
            }

        }
        map1.put("code",Const.SUCCESS_CODE);
        map1.put("message","查询成功");
        map1.put("page",pageInfo);
        map1.put("agentIncomeDetailNews",agentIncomeDetailNews);
        return map1;
    }

    @Override
    public AgentNew getAgentNewByUserId(Long userId) {
        return agentNewMapper.findByUserId(userId);
    }

    @Override
    public Map<String, Object> addAgent(AgentNew agentNew) {
        Map<String,Object> map = new HashMap<>();
        //区县级代理商只能有一个
        if(agentNew.getAgentLevel() == 1){
            Map<String,String> map1 = new HashMap<>();
            map1.put("countyCode",agentNew.getCountyCode());
            List<AgentNew> agentNews = agentNewMapper.selectListVo(map1);
            if(agentNews.size() > 0){
                map.put("code",Const.ERROR_CODE);
                map.put("message","已经存在该区县代理商");
                return map;
            }
        }
        AgentNew agentNew1 = agentNewMapper.findByUserId(agentNew.getUserId());
        if(null != agentNew1){
            map.put("code",Const.ERROR_CODE);
            map.put("message","该用户已经是代理商");
            return map;
        }
        int num = agentNewMapper.insertSelective(agentNew);
        if(num == 1){
            map.put("code",Const.SUCCESS_CODE);
            map.put("message","添加成功");
        }else {
            map.put("code",Const.ERROR_CODE);
            map.put("message","添加失败");
        }
        return map;
    }

    @Override
    public Map<String, Object> findIncomeDetail(String userId,String pageSize,String pageNum,String incomeType) {
        Map<String,Object> map = new HashMap<>();
        if(StringUtils.isEmpty(pageSize)){
            pageSize = "10";
        }
        if(StringUtils.isEmpty(pageNum)){
            pageNum = "1";
        }
        map.put("incomeUserId",userId);
        if(StringUtils.isNotEmpty(incomeType)){
            map.put("incomeType",incomeType);
        }
        map.put("notType",31);
        PageHelper.startPage(Integer.parseInt(pageNum),Integer.parseInt(pageSize));
        List<AgentIncomeDetailNew> agentIncomeDetailNews = agentIncomeDetailNewMapper.findByIncomeUserId(map);
        PageInfo<AgentIncomeDetailNew> pageInfo = new PageInfo<>(agentIncomeDetailNews);
        List<AgentIncomeDetailNew> list = pageInfo.getList();
        for(AgentIncomeDetailNew aNew : list){
            UserInfo userInfo = userInfoMapper.findUserById(aNew.getTriggerIncomeUserId());
            if(null != userInfo){
                aNew.setTriggerIncomePhone(userInfo.getPhone());
                aNew.setTriggerIncomeName(userInfo.getNickName());
            }
        }
        map.clear();
        map.put("code",Const.SUCCESS_CODE);
        map.put("message","查询成功");
        map.put("agentIncomeDetailNews",list);
        map.put("page",pageInfo);
        return map;
    }

    @Override
    public Map<String, Object> findAgentRank(Map<String, Object> map) {
        Map<String,Object> map1 = new HashMap<>();
        int pageSize = 10;
        int pageNum = 1;
        if(StringUtils.isNotEmpty(map.get("pageSize").toString())){
            pageSize = Integer.parseInt(map.get("pageSize").toString());
        }
        if(StringUtils.isNotEmpty(map.get("pageNum").toString())){
            pageNum = Integer.parseInt(map.get("pageNum").toString());
        }
        int order = pageNum * pageSize -9;
        //根据当前登录用户代理级别查询代理商表的userid
        List<Long> userIds = agentNewMapper.findUserIdByMap(map);
        if(userIds.size() <= 0){
            map1.put("code",Const.ERROR_CODE);
            map1.put("message","查无数据");
            return map1;
        }
        map.put("userIds",userIds);
        //按区域广告费总金额排行
        if(map.get("type").toString().equals("1")){

            PageHelper.offsetPage(pageNum,pageSize);
            List<AgentIncomeDetailNew> list = agentIncomeDetailNewMapper.findAgentRank(map);
            PageInfo<AgentIncomeDetailNew> pageInfo = new PageInfo<>(list);
            List<AgentIncomeDetailNew> agentIncomeDetailNews = pageInfo.getList();
            List<AgentRankVo> agentRankVos = new ArrayList<>();
            for(AgentIncomeDetailNew agentIncomeDetailNew : agentIncomeDetailNews){
                AgentRankVo rankVo = new AgentRankVo();
                rankVo.setOrder(order);
                rankVo.setUserId(agentIncomeDetailNew.getIncomeUserId());
                rankVo.setRank(agentIncomeDetailNew.getIncomeAmount().intValue());
                rankVo.setPhone(userInfoMapper.findPhoneByUserId(agentIncomeDetailNew.getIncomeUserId()));
                AgentNew agentNew = agentNewMapper.findByUserId(agentIncomeDetailNew.getIncomeUserId());
                if(null != agentNew){
                    rankVo.setAgentName(agentNew.getAgentName());
                    if(agentNew.getAgentLevel() == 1){
                        rankVo.setAgentLevelStr("区县代理");
                    }else if(agentNew.getAgentLevel() == 2){
                        rankVo.setAgentLevelStr("市级代理");
                    }else if(agentNew.getAgentLevel() == 3){
                        rankVo.setAgentLevelStr("省级代理");
                    }
                }
                agentRankVos.add(rankVo);
                order ++;
            }
            map1.put("code",Const.SUCCESS_CODE);
            map1.put("message","查询成功");
            map1.put("agentRankVos",agentRankVos);
            map1.put("page",pageInfo);
        }else { //按区域用户线下消费流水总金额排行
//            List<AgentNew> agentNews = agentNewMapper.findListByUserId(userIds);
//            for(AgentNew agentNew : agentNews){
//                if(agentNew.getAgentLevel() == 1){
//                    map.put("area",hatAreaMapper.findByAreaId(agentNew.getCountyCode()).getArea());
//                }else if(agentNew.getAgentLevel() == 2){
//                    map.put("city",hatCityMapper.findByCityId(agentNew.getCityCode()).getCity());
//                }else if(agentNew.getAgentLevel() == 3){
//                    map.put("province",hatProvinceMapper.findByProvinceId(agentNew.getProvinceCode()).getProvince());
//                }
//                List<Long> longs = userInfoMapper.findUserIdByMap(map);
//                agentNew.setSumIncome(orderMapper.findSumDealPriceByUserId(longs));
//            }

            PageHelper.startPage(pageNum,pageSize);
            List<AgentRankVo> list = agentNewMapper.findAgentRank(map);
            PageInfo<AgentRankVo> pageInfo = new PageInfo<>(list);
            List<AgentRankVo> agentRankVos = pageInfo.getList();
            for(AgentRankVo rankVo : agentRankVos){
                rankVo.setOrder(order);
                if(rankVo.getAgentLevel() == 1){
                    rankVo.setAgentLevelStr("区县代理");
                }else if(rankVo.getAgentLevel() == 2){
                    rankVo.setAgentLevelStr("市级代理");
                }else if(rankVo.getAgentLevel() == 3){
                    rankVo.setAgentLevelStr("省级代理");
                }
                order ++;
            }

            map1.put("code",Const.SUCCESS_CODE);
            map1.put("message","查询成功");
            map1.put("agentRankVos",agentRankVos);
            map1.put("page",pageInfo);
        }
        return map1;
    }
}
